package sql2pb

import (
	"database/sql"
	"fmt"
	"gctl/internal/sql2pb/logic"
	"log"
	"strings"

	_ "github.com/go-sql-driver/mysql"

	"github.com/spf13/cobra"
)

func Sql2PBRoute(cmd *cobra.Command, args []string) {
	dbType, _ := cmd.Flags().GetString("db")
	host, _ := cmd.Flags().GetString("host")
	port, _ := cmd.Flags().GetInt("port")
	user, _ := cmd.Flags().GetString("user")
	password, _ := cmd.Flags().GetString("password")
	schema, _ := cmd.Flags().GetString("schema")
	table, _ := cmd.Flags().GetString("table")
	serviceName, _ := cmd.Flags().GetString("service_name")
	packageName, _ := cmd.Flags().GetString("package")
	goPackageName, _ := cmd.Flags().GetString("go_package")
	ignoreTableStr, _ := cmd.Flags().GetString("ignore_tables")
	ignoreColumnStr, _ := cmd.Flags().GetString("ignore_columns")
	fieldStyle, _ := cmd.Flags().GetString("field_style")
	protoFile, _ := cmd.Flags().GetString("proto")
	if protoFile != "" {
		logic.Proto2Pb(protoFile)
		return
	}

	if schema == "" {
		fmt.Println(" - please input the database schema ")
		return
	}
	connStr := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, password, host, port, schema)
	db, err := sql.Open(dbType, connStr)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	ignoreTables := strings.Split(ignoreTableStr, ",")
	ignoreColumns := strings.Split(ignoreColumnStr, ",")
	s, err := logic.GenerateSchema(db, table, ignoreTables, ignoreColumns, serviceName, goPackageName, packageName, fieldStyle)
	if nil != err {
		log.Fatal(err)
	}
	if nil != s {
		fmt.Println(s)
	}
	return
}
